package com.zy.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.http.HttpResponse;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-07 周四 16:31
 * @since 17
 */
@RestController
public class DownController {
    @RequestMapping("/dn")
    public void down (HttpServletRequest req, HttpServletResponse resp, HttpSession session){
        String filename = "1.png";
        String f = "WEB-INF/download/"+filename;
        String ff = req.getServletContext().getRealPath(f);
        System.out.println(ff);
        //设置强制下载不打开
        resp.setContentType("application/force-download");
        // 设置文件名字
        resp.addHeader("Content-Disposition","attachment;fileName=" + filename);
        resp.setContentType("application/octet-stream");

        try (FileInputStream fis = new FileInputStream(ff);  ServletOutputStream os = resp.getOutputStream();) {
            byte[] bytes = fis.readAllBytes();
            resp.addHeader("Content-Length","" + bytes.length);
            os.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
